import React from "./react";
import ReactDOM from "./react-dom";

// 类组件的ref
class InputComponent extends React.Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
    }
    onFocus = () => {
        this.inputRef.current.focus();
    };

    render() {
        return (
            <div>
                <input ref={this.inputRef}></input>;
            </div>
        );
    }
}

// 函数式组件的ref
function InputFunComponent(props, ref) {
    return (
        <div>
            <input ref={ref}></input>;
        </div>
    );
}
let ForwardInput = React.forwardRef(InputFunComponent);
{
    /* <ForwardInput /> 
    babel ==>
    ref: undefined
    type: {
    $$typeofs: Symbol(react.forward_ref)
    render: InputFunComponent(props, ref)
    }
*/
}
class ClassComponent extends React.Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
        this.textRef = React.createRef();
        this.classRef = React.createRef();
        this.forwardFunRef = React.createRef();
    }

    onChange = (event) => {
        this.textRef.current.innerText = this.inputRef.current.value || "";
    };

    focusInputComponent = () => {
        this.classRef.current.onFocus();
    };

    focusInputFunComponent = () => {
        this.forwardFunRef.current.focus();
    };

    render() {
        return (
            <div>
                <input ref={this.inputRef}></input>
                <button onClick={this.onChange}>{"onChange="}</button>
                <h1 style={this.props.style} ref={this.textRef}></h1>

                <div>
                    <InputComponent ref={this.classRef} />
                    <button onClick={this.focusInputComponent}>{"InputComponent focus"}</button>
                </div>

                <div>
                    <ForwardInput ref={this.forwardFunRef} />
                    <button onClick={this.focusInputFunComponent}>
                        {"InputFunComponent focus"}
                    </button>
                </div>
            </div>
        );
    }
}

const rootElement = <ClassComponent name="aaaa" style={{ color: "red" }}></ClassComponent>;

ReactDOM.render(rootElement, document.getElementById("root"));

// 核心思想
// 1. 原生组件ref：createDom 最后生产真实Dom时，vDom的ref.crrent = 真实Dom
// 2. class组件ref：new Class的instance，vDom的ref.crrent = instance
// 3. 函数组件ref：通过React.forwardRef，函数组件（props,ref）,type.render（props,ref）

// babel ==>函数组件ref
// ref: undefined
// type: {
// $$typeofs: Symbol(react.forward_ref)
// render: InputFunComponent(props, ref)
// }
